package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paishen.common.LibCommon;
import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.database.Coupon;
import com.paishen.peiniwan.database.CouponDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.widget.InputEditLayout;
import com.paishen.common.widget.MaterialHeader;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;



public class MainProfileCouponLayout extends LinearLayout {
    /**
     * 优惠码长度固定为13位[8位数字+5位字母]
     */
    private final static int COUPON_CODE_LENGTH = 13;

    private final PtrFrameLayout layPtrFrame;
    private final RecyclerView viewRecycler;
    private final CouponAdapter adapter;

    private AlertDialog dlgCouponAdd;
    private boolean isValid = false;

    public MainProfileCouponLayout(Context context) {
        this(context, null);
    }

    public MainProfileCouponLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });

        LayoutInflater.from(context).inflate(R.layout.frame_layout_recycler_simple, this);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        viewRecycler.setAdapter(adapter = new CouponAdapter());
        viewRecycler.setItemAnimator(new DefaultItemAnimator());

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px( 15), 0, BaseUtil.dip2px( 10));
        header.setPtrFrameLayout(layPtrFrame);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                long uid = App.i().getUser().getId();

                requestGet(uid, isValid);
            }
        });

        CouponDao couponDao = App.i().getCurrDaoSession().getCouponDao();
        List<Coupon> couponList = couponDao.queryBuilder().where(CouponDao.Properties.UserId.eq(App.i().getUser().getId())).list();
        adapter.set(couponList);
    }

    public void setValidMode(boolean isValid) {
        this.isValid = isValid;
    }

    private void requestAdd(long uid, String code) {
        final LoadingDialog dlgLoading = new LoadingDialog.Builder(getContext()).create();
        dlgLoading.show();
        PnwHttpManager.Coupon.add(((BaseActivity) getContext()).TAG,code, new PnwOkCallbackAdapter<HttpRespData<com.paishen.peiniwan.frame.http.entity.Coupon>>() {
            @Override
            public void onResponse(HttpRespData<com.paishen.peiniwan.frame.http.entity.Coupon> response, boolean fresh) {
                super.onResponse(response, fresh);
                dlgLoading.dismiss();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    CouponDao couponDao = App.i().getCurrDaoSession().getCouponDao();
                    com.paishen.peiniwan.database.Coupon dbCoupon = ModelConverter.mergeOrReplace(null, response.data, App.i().getUser().getId());
                    couponDao.insertInTx(dbCoupon);
                    adapter.add(dbCoupon);

                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE){
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                dlgLoading.dismiss();
            }
        });

        CouponDao couponDao = App.i().getCurrDaoSession().getCouponDao();
        List<com.paishen.peiniwan.database.Coupon> couponList = couponDao.queryBuilder().where(CouponDao.Properties.UserId.eq(App.i().getUser().getId())).list();
        adapter.set(couponList);
    }

    private void requestGet(long uid, boolean is_valid) {

        PnwHttpManager.Coupon.get(((BaseActivity) getContext()).TAG,  is_valid, new PnwOkCallbackAdapter<HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Coupon>>>() {
            @Override
            public void onResponse(HttpRespData<List<com.paishen.peiniwan.frame.http.entity.Coupon>> response, boolean fresh) {
                super.onResponse(response, fresh);
                layPtrFrame.refreshComplete();
                if (response.errcode == C.http.RESULT_SUCCESS) {
                    CouponDao couponDao = App.i().getCurrDaoSession().getCouponDao();
                    List<com.paishen.peiniwan.database.Coupon> couponList = new ArrayList<>();
                    for (com.paishen.peiniwan.frame.http.entity.Coupon c : response.data) {
                        couponList.add(ModelConverter.mergeOrReplace(null, c, App.i().getUser().getId()));
                    }
                    couponDao.insertOrReplaceInTx(couponList);
                    adapter.set(couponList);
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE){
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                layPtrFrame.refreshComplete();
            }
        });
    }

    public final void showCouponAddDialog() {
        if (dlgCouponAdd == null) {
            FrameLayout content = new FrameLayout(getContext());
            final float scale = getContext().getResources().getDisplayMetrics().density;
            int spacing = (int) (20 * scale + 0.5f);
            content.setPadding(spacing, spacing, spacing, 0);

            final InputEditLayout layEditCode = new InputEditLayout(getContext());
            layEditCode.setInputMaxLength(COUPON_CODE_LENGTH);
            layEditCode.setInputHintColor(0xFFB3B3B3);
            layEditCode.setInputHintText(R.string.balance_coupon_input_hint);
            content.addView(layEditCode);

            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setTitle(R.string.balance_tips_coupon_add).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dlgCouponAdd.dismiss();
                }
            }).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    final String code = layEditCode.getText().toString();
                    if (code.length() != COUPON_CODE_LENGTH) {
                        BaseUtil.showToast(R.string.balance_coupon_error_code);
                        layEditCode.setText("");
                        return;
                    }
                    dlgCouponAdd.dismiss();
                    String formatCode = code.substring(0, 4) + " " + code.substring(4, 8) + " " + code.substring(8);
                    long uid = App.i().getUser().getId();
                    requestAdd(uid, formatCode);
                    layEditCode.setText("");
                }
            });
            builder.setView(content);
            dlgCouponAdd = builder.create();
        }
        dlgCouponAdd.show();
    }

    public interface OnItemClickListener {
        void onCouponClick(com.paishen.peiniwan.database.Coupon coupon);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.adapter.onItemClickListener = onItemClickListener;
    }

    private static final class CouponAdapter extends RecyclerView.Adapter<CouponAdapter.ViewHolder> {
        private OnItemClickListener onItemClickListener;
        final List<com.paishen.peiniwan.database.Coupon> couponList = new ArrayList<>();

        public void add(Coupon data) {
            couponList.add(0, data);
            notifyItemChanged(0);
        }

        public void set(List<Coupon> dataList) {
            couponList.clear();
            couponList.addAll(dataList);
            notifyItemRangeChanged(0, getItemCount());
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements OnClickListener {
            public ViewHolder(View view) {
                super(view);
                view.setOnClickListener(this);
            }

            private Coupon itemData;
            private TextView txValue, txValueInfo, txTimeRange;
            private ImageView imgValidTag, imgFlag;

            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) onItemClickListener.onCouponClick(itemData);
            }
        }

        @Override
        public int getItemCount() {
            return couponList.size();
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_main_profile_coupon, viewGroup, false);
            ViewHolder viewHolder = new ViewHolder(view);
            viewHolder.txValue = (TextView) view.findViewById(R.id.tx_value);
            viewHolder.txValueInfo = (TextView) view.findViewById(R.id.tx_value_info);
            viewHolder.txTimeRange = (TextView) view.findViewById(R.id.tx_time_range);
            viewHolder.imgValidTag = (ImageView) view.findViewById(R.id.img_valid_tag);
            viewHolder.imgFlag = (ImageView) view.findViewById(R.id.img_flag);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
            final Coupon coupon = couponList.get(i);
            viewHolder.txValue.setText(App.i().getString(R.string.date_pay_value, String.valueOf((int) coupon.getAmount())));
            viewHolder.txValue.setTextColor(coupon.getIs_valid() ? 0xff8c6ce7 : 0xffb4b3b4);
            viewHolder.txValueInfo.setText(App.i().getString(R.string.balance_coupon_value_info, String.valueOf((int) coupon.getAmount())));
            viewHolder.txValueInfo.setTextColor(coupon.getIs_valid() ? 0xff675857 : 0xffb4b3b4);
            viewHolder.txTimeRange.setText(App.i().getString(R.string.balance_coupon_time_range, coupon.getValid_from(), coupon.getValid_to()));
            viewHolder.imgValidTag.setVisibility(coupon.getIs_valid() ? View.GONE : View.VISIBLE);
            viewHolder.imgFlag.setImageResource(coupon.getIs_valid() ? R.drawable.main_profile_shape_coupon_flag_purple : R.drawable.main_profile_shape_coupon_flag_gray);
            viewHolder.itemData = coupon;
        }
    }



}
